// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import { UNetMgr } from "../UNet/UNetMgr";
import FrameStep from "./FrameStep";

const {ccclass, property} = cc._decorator;

@ccclass
export default class Game extends cc.Component {
    @property(cc.Prefab)
    bulletPrefab : cc.Prefab = null;

    public static get Instance(){
        return this.s_instance
    }
    private static s_instance:Game;

    frameUnits : Array<FrameStep> = [];

    onLoad(){
        Game.s_instance = this;
        UNetMgr.SendRoomMsg('ready',{})
        UNetMgr.event.on('frameUpdate',this.OnFrameUpdate,this)
        UNetMgr.event.on('close',()=>{
            console.log('重连失败，退出游戏')
            this.node.destroy();
        },this)
        UNetMgr.event.on('reconnect',()=>{
            console.log('断线重连中')
        },this)
    }
    
    removeBullet(fs:FrameStep){
        var idx = this.frameUnits.findIndex(v=>{return v._uuid == fs._uuid});
        if(idx >= 0){
            this.frameUnits.splice(idx,1);
            fs.node.destroy();
        }
    }
    
    addBullet(uuid:string,type:number,x:number,y:number){
        var node = cc.instantiate(this.bulletPrefab);
        this.node.getChildByName('Bullet').addChild(node);
        var fs = node.getComponent(FrameStep)
        fs.initFrame(uuid,UNetMgr.room.frame,{type:type,x:x,y:y})
        this.frameUnits.push(fs)
    }

    OnFrameUpdate(frame:number){
        for(var i=0; i<this.frameUnits.length; i++){
            var fs = this.frameUnits[i];
            fs.OnSyncFrame(UNetMgr.room.frame);
        }
    }

    onDestroy(){
        UNetMgr.event.off(this);
    }
}
